/*
 * Copyright (c) Jack魏 2023 - 2023, All Rights Reserved.
 */

package cn.jackwei.yiyi.exception;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import cn.dev33.satoken.exception.NotLoginException;
import cn.jackwei.yiyi.pojo.enums.SymbolEnum;
import cn.jackwei.yiyi.util.Result;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理
 *
 * @author Jack魏
 * @since 2023/11/6 22:56
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 这里处理Exception异常的信息，ResponseStatus这个就是返回前端的状态码（去掉响应是200，否则是500）
     *
     * @param request   请求
     * @param exception 异常
     * @return 返回错误信息
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<String> handleException(HttpServletRequest request, Exception exception) {
        // 如果没有这个，是不会打印错误日志信息的
        log.error(exception.getMessage(), exception);
        return Result.fail(exception.getMessage());
    }

    /**
     * 参数验证错误
     *
     * @param request   请求
     * @param exception 异常
     * @return 返回错误信息
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<String> handleViolationException(HttpServletRequest request, ConstraintViolationException exception) {
        final Set<ConstraintViolation<?>> constraintViolations = exception.getConstraintViolations();
        List<String> messages = new ArrayList<>();
        constraintViolations.forEach(item -> {
            messages.add(item.getMessage());
        });
        return Result.fail(messages.stream().collect(Collectors.joining(SymbolEnum.COMMA.getCn())));
    }

    /**
     * 实体类参数验证错误
     *
     * @param request   请求
     * @param exception 异常
     * @return 返回错误信息
     */
    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<String> handleViolationException(HttpServletRequest request, BindException exception) {
        final List<ObjectError> allErrors = exception.getAllErrors();
        List<String> messages = new ArrayList<>();
        allErrors.forEach(item -> {
            messages.add(item.getDefaultMessage());
        });
        return Result.fail(messages.stream().collect(Collectors.joining(SymbolEnum.COMMA.getCn())));
    }

    /**
     * 业务异常
     *
     * @param request   请求
     * @param exception 异常
     * @return 返回错误信息
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<String> handleException(HttpServletRequest request, BusinessException exception) {
        return Result.fail(exception.getMessage());
    }

    /**
     * 未登录异常
     *
     * @param request   请求
     * @param exception 异常
     * @return 返回错误信息
     */
    @ExceptionHandler(NotLoginException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<String> handleException(HttpServletRequest request, NotLoginException exception) {
        return Result.fail("未登录，请先登录再操作！");
    }
}
